package org.apache.ibatis.demo;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.demo.bean.User;
import org.apache.ibatis.demo.consts.UserStatement;
import org.apache.ibatis.demo.factory.DemoSqlSessionFactory;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Demo1
 *
 * @author zhaohui
 * @date 2019/8/27 20:51
 */
public class Demo1 {

    private static final DemoSqlSessionFactory sqlSessionFactory = new DemoSqlSessionFactory();

    public static void main(String[] args) {
        Demo1 demo = new Demo1();
//        List<User> users = demo.getByUserNameAndIdCard("魏俊翠", "654779430425900939");
//        System.out.println("queryResult= " + users);
//        demo.insert();

        // 批量插入
//        demo.batchInsert();

        int lastId = demo.lastId();
        System.out.println(lastId);

        // 分页
//        RowBounds rowBounds = new RowBounds(0, 5);
//        List<User> users = demo.queryForPage(rowBounds);
//        users.forEach(System.out::println);
//        System.out.println(user);


    }

    private int lastId() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        if (null == sqlSession) {
            System.out.println("open session exception exception!");
            return 0;
        }
        return sqlSession.selectOne("org.apache.ibatis.demo.UserDao.lastId");
    }

    private User getById(int id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        if (null == sqlSession) {
            return null;
        }
        // getMapper实际获取的是代理对象，底层调用的依然是sqlSession的方法
        return sqlSession.getMapper(UserDao.class).getById(id);
    }

    private List<User> getByUserNameAndIdCard(String name, String idCard) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        if (null == sqlSession) {
            System.out.println("open session exception exception!");
            return null;
        }
        Map<String, Object> params = new HashMap<>(2);
        params.put("userName", name);
        params.put("idCard", idCard);
        return sqlSession.selectList("org.apache.ibatis.demo.UserDao.getByUserNameAndIdCard", params);
    }

    private List<User> queryForPage(RowBounds rowBounds) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PageHelper.startPage(rowBounds.getOffset(), rowBounds.getLimit());
        List<User> users = sqlSession.selectList(UserStatement.SELECT_FOR_PAGE1, 10000);
        return users;
    }

}
